package com.ruoyi.web.controller.api;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.cms.domain.vo.CmsArticleVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.serve.domain.bo.ServeTaskBo;
import com.ruoyi.serve.domain.bo.ServeTaskItemBo;
import com.ruoyi.serve.domain.vo.ServeTaskItemVo;
import com.ruoyi.serve.domain.vo.ServeTaskVo;
import com.ruoyi.serve.service.IServeTaskItemService;
import com.ruoyi.serve.service.IServeTaskService;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 服务任务
 *
 * @author ruoyi
 * @date 2022-11-03
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/serveTask")
public class ApiServeTaskController extends BaseController {

    private final IServeTaskService iServeTaskService;

    private final IServeTaskItemService serveTaskItemService;

    private final ISysOssService iSysOssService;
    /**
     * 查询服务任务列表
     */
    @GetMapping("/list")
    public TableDataInfo<ServeTaskVo> list(ServeTaskBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        bo.setUserId(loginUser.getUserId());
        return iServeTaskService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询服务任务详情
     */
    @GetMapping("/getTaskInfo")
    public R<ServeTaskVo> getTaskInfo(Long id) {
        return R.ok(iServeTaskService.queryById(id));
    }

    /**
     * 查询服务项目详情
     */
    @GetMapping("/getTaskItemInfo")
    public R<ServeTaskItemVo> getTaskItemInfo(Long id) {
        return R.ok(serveTaskItemService.queryById(id));
    }




    /**
     * 服务签到：按服务项目
     */
    @GetMapping("/sign")
    public R sign(Long id) {
        ServeTaskItemVo serveTaskItemVo = serveTaskItemService.queryById(id);
        serveTaskItemVo.setSignTime(new Date());
        serveTaskItemVo.setStatus("1");
        serveTaskItemService.updateByBo(BeanUtil.toBean(serveTaskItemVo, ServeTaskItemBo.class));
        return R.ok();
    }




    /**
     * 完成服务项目
     */
    @GetMapping("/finishTaskItem")
    public R<ServeTaskItemVo> finishTaskItem(Long id,String evaluate) {
        ServeTaskItemVo serveTaskItemVo = serveTaskItemService.queryById(id);
        serveTaskItemVo.setStatus("2");
        serveTaskItemVo.setFinishTime(new Date());
        serveTaskItemVo.setEvaluate(evaluate);
        serveTaskItemService.updateByBo(BeanUtil.toBean(serveTaskItemVo, ServeTaskItemBo.class));
        //检查所有项目是否完成，如果已完成，那么整个任务完成
        Long taskId = serveTaskItemVo.getTaskId();
        ServeTaskItemBo serveTaskItemBo = new ServeTaskItemBo();
        serveTaskItemBo.setTaskId(taskId);
        List<ServeTaskItemVo> serveTaskItemVoList = this.serveTaskItemService.queryList(serveTaskItemBo);
        boolean allFinish = serveTaskItemVoList.stream().allMatch(i->"2".equals(i.getStatus()));
        ServeTaskVo serveTaskVo =  iServeTaskService.queryById(taskId);
        if(allFinish){
            //如果所有项目都完成了，那么整个任务就完成了
            serveTaskVo.setStatus("2");
        }else{
            //如果整个项目没有完成，那么整个任务就是进行中
            serveTaskVo.setStatus("1");
        }
        iServeTaskService.updateByBo(BeanUtil.toBean(serveTaskVo,ServeTaskBo.class));

        return R.ok();
    }

    /**
     * 上传项目开始前照片
     * @param file
     * @param taskItemId
     * @return
     */
    @PostMapping(value = "/uploadTaskItemBeforeImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> uploadTaskItemBeforeImage(@RequestPart("file") MultipartFile file,Long taskItemId){
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOss oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());

        ServeTaskItemVo serveTaskItem = serveTaskItemService.queryById(taskItemId);
        if(StringUtils.isNotEmpty(serveTaskItem.getBeforeImgs())){
            serveTaskItem.setBeforeImgs(serveTaskItem.getBeforeImgs()+";"+oss.getUrl());
        }else{
            serveTaskItem.setBeforeImgs(oss.getUrl());
        }
        serveTaskItem.setSignTime(new Date());
        serveTaskItemService.updateByBo(BeanUtil.toBean(serveTaskItem, ServeTaskItemBo.class));
        return R.ok(map);
    }

    /**
     * 上传项目开始后照片
     * @param file
     * @param taskItemId
     * @return
     */
    @PostMapping(value = "/uploadTaskItemAfterImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> uploadTaskItemAfterImage(@RequestPart("file") MultipartFile file,Long taskItemId){
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOss oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());

        ServeTaskItemVo serveTaskItem = serveTaskItemService.queryById(taskItemId);
        if(StringUtils.isNotEmpty(serveTaskItem.getAfterImgs())){
            serveTaskItem.setAfterImgs(serveTaskItem.getAfterImgs()+";"+oss.getUrl());
        }else{
            serveTaskItem.setAfterImgs(oss.getUrl());
        }

        serveTaskItemService.updateByBo(BeanUtil.toBean(serveTaskItem, ServeTaskItemBo.class));
        return R.ok(map);
    }





    /**
     * 批量完成服务项目
     */
    @GetMapping("/batchFinishTaskItem")
    public R<ServeTaskItemVo> batchFinishTaskItem() {
        //检查所有项目是否完成，如果已完成，那么整个任务完成
        ServeTaskBo serveTaskBo = new ServeTaskBo();
        serveTaskBo.setBeginTime(DateUtils.parseDate("2023-02-01"));
        serveTaskBo.setEndTime(DateUtils.parseDate("2023-03-01"));
        List<ServeTaskVo> taskVoList = this.iServeTaskService.queryList(serveTaskBo);
        for(int i = 0 ; i < taskVoList.size(); i++){
            ServeTaskVo taskVo = taskVoList.get(i);

            Long taskId = taskVo.getId();
            ServeTaskItemBo serveTaskItemBo = new ServeTaskItemBo();
            serveTaskItemBo.setTaskId(taskId);
            List<ServeTaskItemVo> serveTaskItemVoList = this.serveTaskItemService.queryList(serveTaskItemBo);
            boolean allFinish = serveTaskItemVoList.stream().allMatch(item->"2".equals(item.getStatus()));
            if(allFinish){
                //如果所有项目都完成了，那么整个任务就完成了
                taskVo.setStatus("2");
                iServeTaskService.updateByBo(BeanUtil.toBean(taskVo,ServeTaskBo.class));
            }else{
                //如果整个项目没有完成，那么整个任务就是进行中
                taskVo.setStatus("1");
            }
        }
        return R.ok();
    }

    /**
     * 删除已完成但是没有任务项目的服务任务
     */
    @GetMapping("/deleteTask")
    public R deleteTask() {
        //检查所有项目是否完成，如果已完成，那么整个任务完成
        ServeTaskBo serveTaskBo = new ServeTaskBo();
        serveTaskBo.setBeginTime(DateUtils.parseDate("2023-02-01"));
        serveTaskBo.setEndTime(DateUtils.parseDate("2023-03-01"));
//        serveTaskBo.setUserId(1621399601530609665L);
        serveTaskBo.setStatus("2");
        List<ServeTaskVo> taskVoList = this.iServeTaskService.queryList(serveTaskBo);

        List<Long> ids = new ArrayList<>();
        for(int i = 0 ; i < taskVoList.size(); i++){
            ServeTaskVo taskVo = taskVoList.get(i);

            Long taskId = taskVo.getId();

            ServeTaskItemBo serveTaskItemBo = new ServeTaskItemBo();
            serveTaskItemBo.setTaskId(taskId);
            List<ServeTaskItemVo> serveTaskItemVoList = this.serveTaskItemService.queryList(serveTaskItemBo);
            if(serveTaskItemVoList==null || serveTaskItemVoList.size()<=0){
                ids.add(taskId);
            }

        }
        if(ids.size()>0){
            iServeTaskService.deleteWithValidByIds(ids,true);
        }
        return R.ok();
    }


}
